package com.cn.xiongmeng.czlxz.utils;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.cn.xiongmeng.czlxz.MainActivity;
import com.cn.xiongmeng.czlxz.activity.IndexActivity;
import com.cn.xiongmeng.czlxz.network.HttpClient;
import com.github.gzuliyujiang.oaid.DeviceID;
import com.github.gzuliyujiang.oaid.DeviceIdentifier;
import com.github.gzuliyujiang.oaid.IGetter;

import org.json.JSONException;
import org.json.JSONObject;

public class DeviceIdUtils {
    private static final String TAG = "DeviceIdUtils";

    public static void sendIdsToServer(Context context){
        String androidId = getAndroidId(context);
        String pseudoId = getPseudoId();

        // Log.d(TAG, "androidId: " + androidId);
        // Log.d(TAG, "pseudoId: " + pseudoId);

        // getOaidAndSendAllIdsToServer(context, androidId, pseudoId);
        oaidConfirm(context, androidId, pseudoId);
    }

    public static String getAndroidId(Context context){
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    public static String getPseudoId(){
        // 根据硬件信息生成，有大概率会重复，不会为空
        return DeviceIdentifier.getPseudoID();
    }

    private static void oaidConfirm(Context context, String androidId, String pseudoId){
        // 1、缓存中，存的oaidIsAgreed为true，直接获取oaid
        SharedPreferences prefs = context.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        boolean oaidIsAgreed = prefs.getBoolean("oaidIsAgreed", false);

        if (oaidIsAgreed) {
            // 用户同意收集OAID，可以在这里调用获取OAID的方法
            getOaidAndSendAllIdsToServer(context, androidId, pseudoId);
        } else {
            sendJSONDataToServer(context, androidId, pseudoId, "none");
        }
    }

    public static void getOaidAndSendAllIdsToServer(Context context, String androidId, String pseudoId){
        //HashMap<String, Boolean> map = new HashMap<>();
        //map.put("isSupported", false); // 是否支持
        //map.put("successObtain", false); // 是否成功拿到oaid

        boolean isSupported = DeviceID.supportedOAID(context);

        if (isSupported){

            DeviceID.getOAID(context, new IGetter() {
                @Override
                public void onOAIDGetComplete(String result) {
                    // 获取成功
                    Log.d(TAG, "oaid: " + result);
                    sendJSONDataToServer(context, androidId, pseudoId, result);
                }

                @Override
                public void onOAIDGetError(Exception error) {
                    // 获取失败
                    sendJSONDataToServer(context, androidId, pseudoId, "none");
                }
            });
        } else {
            sendJSONDataToServer(context, androidId, pseudoId, "notSupport");
            // Toast.makeText(context, "不支持获取oaid", Toast.LENGTH_LONG).show();
        }
    }
    private static void sendJSONDataToServer(Context context, String androidId, String pseudoId, String oaid){
        // 请求成功的话，会返回uid
        // 请求失败的话，会返回相应code
        String jsonString = null;
        try {
            JSONObject jsonObject = new JSONObject();

            String key1 = "androidId";
            String key2 = "pseudoId";
            String key3 = "oaid";
            jsonObject.put(key1, androidId);
            jsonObject.put(key2, pseudoId);
            jsonObject.put(key3, oaid);

            jsonString = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.d(TAG, "jsonString: " + jsonString);

        HttpClient httpClient = new HttpClient(context);
        String url = "https://little-moon.fun/get_fake_user/";

        httpClient.sendPostRequest(url, jsonString, new HttpClient.Callback() {
            @Override
            public void onFailure(Exception e) {
                // 测试成功
                // Log.e(TAG, "Post 请求失败", e); // Log 错误信息
                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(context, "请稍后再试！", Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Post 请求成功: " + response); // Log 成功响应
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    if (code.equals("401")){
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Toast.makeText(context, "IP聚集，明日再试。", Toast.LENGTH_LONG).show();
                            System.exit(0);
                        });
                    } else {
                        // Log.d(TAG, "Post 请求成功: " + response); // Log 成功响应
                        SharedPreferences prefs = context.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        String key = "fakeUser";
                        editor.putString(key, response);
                        editor.apply(); // apply异步，commit同步
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                /*try {
                    JSONObject jsonObject = new JSONObject(response);
                    String totalTl = jsonObject.getString("total_tl");

                } catch (JSONException e) {
                    e.printStackTrace();
                }*/
            }
        });
    }
}
